package com.epfresh.supplier.activity;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.InputFilter;
import android.text.TextUtils;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.TextView;

import com.epfresh.api.dialog.PackagePriceDialog;
import com.epfresh.api.entity.RequestEntityMapSupply;
import com.epfresh.api.entity.ResponseEntity;
import com.epfresh.api.entity.StatusEntity;
import com.epfresh.api.global.AppActivity;
import com.epfresh.api.http.OnRequestListener;
import com.epfresh.api.utils.CashierInputFilter;
import com.epfresh.supplier.R;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by wzh on 16-7-25.
 */
public class ProductAddPriceActivity extends AppActivity {


    private TextView tvPackageUnit;
    private TextView tvTitle;
    private EditText edPackage;

    private View vPreTips;
    private View vFlag;

    private String unit;
    private String value;
    private String productId;
    private String price;
    private int saleType = 1;
    private List<String> priceUnit ;

    private String priceUnitStr;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_product_price);

        if (savedInstanceState != null) {
            getIntent().putExtra("productId", savedInstanceState.getString("productId"));
            getIntent().putExtra("price", savedInstanceState.getString("price"));
            getIntent().putExtra("type", savedInstanceState.getInt("type", -1));
            getIntent().putExtra("unit", savedInstanceState.getString("unit"));
            getIntent().putExtra("value", savedInstanceState.getString("value"));
            getIntent().putExtra("saleType", savedInstanceState.getInt("saleType"));
            getIntent().putExtra("priceUnit", savedInstanceState.getString("priceUnit"));

        }

        toolbarTitle.setText("价格");
        ivBack.setVisibility(View.VISIBLE);
        tvBack.setVisibility(View.VISIBLE);

        rightbtn.setText("保存");

        rightbtn.setVisibility(View.VISIBLE);

        tvPackageUnit = (TextView) findViewById(R.id.tv_package);
        tvTitle = (TextView) findViewById(R.id.tv_title);
        edPackage = (EditText) findViewById(R.id.ed_package);
        vPreTips =  findViewById(R.id.rl_refuse_reason);
        vFlag =  findViewById(R.id.iv_flag);
        tvPackageUnit.setOnClickListener(this);
        CashierInputFilter cashierInputFilter = new CashierInputFilter();
        cashierInputFilter.MAX_VALUE = 99999;
        edPackage.setFilters(new InputFilter[]{cashierInputFilter});
        findViewById(R.id.tv_btn).setOnClickListener(this);


        unit = getIntent().getStringExtra("unit");
        value = getIntent().getStringExtra("price");
        productId = getIntent().getStringExtra("productId");
        price = getIntent().getStringExtra("price");
        edPackage.setText(value);
        edPackage.setSelection(edPackage.length());

        priceUnitStr = getIntent().getStringExtra("priceUnit");
        if (priceUnitStr != null && !"".equals(priceUnitStr)){
            priceUnit = new Gson().fromJson(priceUnitStr,new TypeToken<List<String>>(){}.getType());
        }

        if (priceUnit == null){
            priceUnit = new ArrayList<>();
        }

        if (priceUnit.size() == 0){
            vFlag.setVisibility(View.INVISIBLE);
        }else {
            vFlag.setVisibility(View.VISIBLE);

        }

        if (!TextUtils.isEmpty(unit)) {
            tvPackageUnit.setText("元/" + unit);
        } else {
            tvPackageUnit.setText("元");
        }

        saleType = getIntent().getIntExtra("saleType",1);
        if (saleType == 2){
            vPreTips.setVisibility(View.VISIBLE);
        }else {
            vPreTips.setVisibility(View.GONE);

        }
    }

    @Override
    public void onRightClick() {
        save();
    }

    @Override
    public void onClick(View view) {
        super.onClick(view);
        switch (view.getId()) {

            case R.id.tv_btn:
                save();
                break;
            case R.id.tv_package:
                openUnitDialog(priceUnit);
                break;

        }
    }

    private void save() {

        if (TextUtils.isEmpty(edPackage.getText().toString())) {

            toast("请输入价格");

            return;
        }


        InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.hideSoftInputFromWindow(edPackage.getWindowToken(), 0); //强制隐藏键盘

        if (productId != null && !"".equals(productId)) {
            requestProductModify(edPackage.getText().toString());

        } else {
            Intent intent = new Intent();
            intent.putExtra("result", edPackage.getText().toString());
            intent.putExtra("unit", unit);
            setResult(RESULT_OK, intent);
            finish();
        }
    }




    public void openUnitDialog(List<String> units) {

        if (priceUnit == null || priceUnit.size() == 0){
            return;
        }
        PackagePriceDialog packageDialog = new PackagePriceDialog(this);
        packageDialog.setPositiveDismiss(true);
        packageDialog.setOnPositiveClickListener(new PackagePriceDialog.OnPositiveClickListener() {
            @Override
            public void onPositiveClickListener(int index1, String data1) {
                unit = data1;
                tvPackageUnit.setText("元/"+data1);

            }
        });

        packageDialog.setData(priceUnit);

//        String packageUnit = productAddEntity.getPackageUnit();
//        String packageContainer = productAddEntity.getPackageContainer();

        if (!TextUtils.isEmpty(unit)) {
            int index1 = 0;

            for (int i = 0; i < units.size(); i++) {
                if (unit.equals(units.get(i))) {
                    index1 = i;
                }
            }

            packageDialog.setCurrentItem(index1);
        }

        packageDialog.show();
    }


    @Override
    protected void onSaveInstanceState(Bundle outState) {

        outState.putString("unit", unit);
        outState.putString("value", value);
        outState.putString("productId", productId);
        outState.putString("price", price);
        outState.putString("priceUnit", priceUnitStr);
        outState.putInt("saleType", saleType);
        super.onSaveInstanceState(outState);
    }


    @Override
    protected void onToolbarBack() {
        InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.hideSoftInputFromWindow(edPackage.getWindowToken(), 0); //强制隐藏键盘
        super.onToolbarBack();
    }

    @Override
    public void onBackPressed() {
        InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.hideSoftInputFromWindow(edPackage.getWindowToken(), 0); //强制隐藏键盘
        super.onBackPressed();
    }

    private void requestProductModify(String moq) {

        RequestEntityMapSupply RequestEntityMapSupply = new RequestEntityMapSupply();
        RequestEntityMapSupply.setCmd(com.epfresh.api.constant.AppSupplyRouterConstant.cmd_store_product_modify);
        RequestEntityMapSupply.putParameter("price", moq);
        RequestEntityMapSupply.putParameter("id", productId);
        request(RequestEntityMapSupply, com.epfresh.api.constant.AppSupplyRouterConstant.cmd_store_product_modify, onProductModifyRequestListener);

    }

    private OnRequestListener<StatusEntity> onProductModifyRequestListener = new OnRequestListener<StatusEntity>() {
        @Override
        public StatusEntity jsonToObj(String responseStr) {
            return new Gson().fromJson(responseStr, StatusEntity.class);
        }

        @Override
        public void onFail(int failCode, Object arg, Object tag) {
            hideProgressDialog();
        }

        @Override
        public void onResponseError(int failCode, Object arg, Object tag) {
            hideProgressDialog();
        }

        @Override
        public void onStart(Object tag) {
            showProgressDialog();
        }

        @Override
        public void onResponse(ResponseEntity<StatusEntity> response, Object tag) {

            hideProgressDialog();
            StatusEntity responseElement = response.getResponseElement();
            if (responseElement.isSuccess()) {
                Intent intent = new Intent();
                intent.putExtra("result", edPackage.getText().toString());
                intent.putExtra("unit", unit);
                setResult(RESULT_OK, intent);
                finish();
            } else {
                //没有数据
                toast("修改失败");

            }

        }
    };
}
